//
//  CBJLoginWebController.swift
//  Weibo
//
//  Created by 崔健 on 16/5/22.
//  Copyright © 2016年 cbj. All rights reserved.
//

import UIKit
import SVProgressHUD


class CBJLoginWebController: UIViewController , UIWebViewDelegate {
    
    
    var webView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self;
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(closeLogin))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: #selector(testAccount))
        
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
        
    }
    
    func testAccount(){
        
        let jsString = "document.getElementById('userId').value = '18763276862', document.getElementById('passwd').value = 'cuijian' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    
    func closeLogin(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        let flag = "code="
        if urlString.containsString(flag){
            
            let range = urlString.rangeOfString(flag)
            let codeString = urlString.substringFromIndex((range?.endIndex)!
            )

            CBJUserAccountViewModel.sharedAccountViewModel.loadAccountToken(codeString, finished: { (isSuccess) in
                
                
                if isSuccess {
                    
                    // 发送通知切换根控制器
                    NSNotificationCenter.defaultCenter().postNotificationName("changeRootVc", object: "welcome")
                }else{
                
                    
                    SVProgressHUD.showErrorWithStatus("世界上最远的距离就是没网")

                    dispatch_after(2, dispatch_get_main_queue(), {
                        
                        SVProgressHUD.dismiss()
                    })
                    
                }

            })
            
            return false
        }
        
        return true
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    
    
}





